<template>
	<view class="oa-content">
		<!-- 顶部自定义导航 -->
		<tn-nav-bar fixed customBack :bottomShadow="false" backgroundColor="#FFFFFF">
			<view slot="back" class='tn-custom-nav-bar__back' @click="goBack">
				<text class='icon tn-icon-left-arrow'></text>
			</view>
			<view class="tn-flex tn-flex-col-center tn-flex-row-center ">
				<text class="tn-text-bold tn-text-xl tn-color-black">编辑客户</text>
			</view>
		</tn-nav-bar>

		<view class="" :style="{paddingTop: vuex_custom_bar_height + 30 + 'px'}" style="padding-bottom: 240rpx;">

			<!-- 客户名称 -->
			<view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding">
				<view class="justify-content-item tn-flex-1">
					<view class="tn-text-bold tn-text-lg">
						客户名称 <text class="tn-color-red tn-padding-left-xs">*</text>
					</view>
					<view class="tn-color-gray tn-padding-top-xs tn-color-black">
						<input v-model="formData.name" placeholder="请输入客户名称" name="name"
							placeholder-style="color:#AAAAAA" value=""></input>
					</view>
				</view>
				<view class="justify-content-item tn-text-xl tn-color-grey tn-margin-left">
					<view class="tn-icon-user tn-padding-top"></view>
				</view>
			</view>

			<!-- 客户来源 -->
			<picker @change="bindSourceChange" :value="sourceIndex" :range="DICT.crm_customer_source" range-key="label">
				<view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding">
					<view class="justify-content-item tn-flex-1">
						<view class="tn-text-bold tn-text-lg">
							客户来源 <text class="tn-color-red tn-padding-left-xs">*</text>
						</view>
						<view class="tn-color-gray tn-padding-top-xs" v-if="sourceIndex===99">
							请选择
						</view>
						<view class="tn-color-black tn-padding-top-xs" v-else>
							{{DICT.crm_customer_source[sourceIndex].label}}
						</view>
					</view>
					<view class="justify-content-item tn-text-lg tn-color-grey tn-margin-left">
						<view class="tn-icon-right tn-padding-top"></view>
					</view>
				</view>
			</picker>

			<!-- 手机号码 -->
			<view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding">
				<view class="justify-content-item tn-flex-1">
					<view class="tn-text-bold tn-text-lg">
						手机号码
					</view>
					<view class="tn-color-gray tn-padding-top-xs tn-color-black">
						<input v-model="formData.mobile" placeholder="请输入手机号码" name="mobile"
							placeholder-style="color:#AAAAAA" value=""></input>
					</view>
				</view>
				<view class="justify-content-item tn-text-xl tn-color-grey tn-margin-left">
					<view class="tn-icon-phone tn-padding-top"></view>
				</view>
			</view>

			<!-- 固定电话 -->
			<view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding">
				<view class="justify-content-item tn-flex-1">
					<view class="tn-text-bold tn-text-lg">
						固定电话
					</view>
					<view class="tn-color-gray tn-padding-top-xs tn-color-black">
						<input v-model="formData.telephone" placeholder="请输入固定电话" name="telephone"
							placeholder-style="color:#AAAAAA" value=""></input>
					</view>
				</view>
				<view class="justify-content-item tn-text-xl tn-color-grey tn-margin-left">
					<view class="tn-icon-phone tn-padding-top"></view>
				</view>
			</view>

			<!-- 邮箱 -->
			<view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding">
				<view class="justify-content-item tn-flex-1">
					<view class="tn-text-bold tn-text-lg">
						邮箱地址
					</view>
					<view class="tn-color-gray tn-padding-top-xs tn-color-black">
						<input v-model="formData.email" placeholder="请输入邮箱地址" name="email"
							placeholder-style="color:#AAAAAA" value=""></input>
					</view>
				</view>
				<view class="justify-content-item tn-text-xl tn-color-grey tn-margin-left">
					<view class="tn-icon-mail tn-padding-top"></view>
				</view>
			</view>

			<!-- 客户级别 -->
			<picker @change="bindLevelChange" :value="levelIndex" :range="DICT.crm_customer_level" range-key="label">
				<view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding">
					<view class="justify-content-item tn-flex-1">
						<view class="tn-text-bold tn-text-lg">
							客户级别
						</view>
						<view class="tn-color-gray tn-padding-top-xs" v-if="levelIndex===99">
							请选择
						</view>
						<view class="tn-color-black tn-padding-top-xs" v-else>
							{{DICT.crm_customer_level[levelIndex].label}}
						</view>
					</view>
					<view class="justify-content-item tn-text-lg tn-color-grey tn-margin-left">
						<view class="tn-icon-right tn-padding-top"></view>
					</view>
				</view>
			</picker>

			<!-- 客户行业 -->
			<picker @change="bindIndustryChange" :value="industryIndex" :range="DICT.crm_customer_industry" range-key="label">
				<view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding">
					<view class="justify-content-item tn-flex-1">
						<view class="tn-text-bold tn-text-lg">
							客户行业
						</view>
						<view class="tn-color-gray tn-padding-top-xs" v-if="levelIndex===99">
							请选择
						</view>
						<view class="tn-color-black tn-padding-top-xs" v-else>
							{{DICT.crm_customer_industry[industryIndex].label}}
						</view>
					</view>
					<view class="justify-content-item tn-text-lg tn-color-grey tn-margin-left">
						<view class="tn-icon-right tn-padding-top"></view>
					</view>
				</view>
			</picker>

			<!-- 下次联系时间 -->
			<view class="">
				<tn-picker mode="time" v-model="showTimePicker" :params="timeParams" :startYear="startYear"
					:endYear="endYear" @confirm="confirmTimePicker"></tn-picker>
			</view>

			<view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding" @tap="showTimePicker">
				<view class="justify-content-item tn-flex-1">
					<view class="tn-text-bold tn-text-lg">
						下次联系时间
					</view>
					<view class="tn-color-gray tn-padding-top-xs" v-if="formData.contactNextTime===''">
						请选择
					</view>
					<view class="tn-padding-top-xs" v-else>
						{{ formData.contactNextTime }}
					</view>
				</view>
				<view class="justify-content-item tn-text-lg tn-color-grey tn-margin-left">
					<view class="tn-icon-time tn-padding-top"></view>
				</view>
			</view>

			<!-- 地址 -->
			<view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding">
				<view class="justify-content-item tn-flex-1">
					<view class="tn-text-bold tn-text-lg">
						详细地址
					</view>
					<view class="tn-color-gray tn-padding-top-xs tn-color-black">
						<input v-model="formData.detailAddress" placeholder="请输入详细地址" name="detailAddress"
							placeholder-style="color:#AAAAAA" value=""></input>
					</view>
				</view>
				<view class="justify-content-item tn-text-xl tn-color-grey tn-margin-left">
					<view class="tn-icon-location tn-padding-top"></view>
				</view>
			</view>

			<!-- 备注 -->
			<view class="tn-flex tn-flex-row-between tn-flex-col-center tn-padding">
				<view class="tn-flex justify-content-item">
					<view class="tn-text-bold tn-text-lg">
						备注信息
					</view>
				</view>
				<view class="tn-flex justify-content-item tn-color-gray">
					200字内
				</view>
			</view>
			<view class="tn-bg-gray--light tn-padding tn-text-justify"
				style="border-radius: 10rpx;margin: 0 30rpx 30rpx 30rpx;">
				<textarea v-model="formData.remark" maxlength="200" placeholder="请输入备注信息"
					placeholder-style="color:#AAAAAA" style="height: 160rpx;width: 100%;"></textarea>
			</view>

			<!-- 锁定状态 -->
			<picker @change="bindLockStatusChange" :value="lockStatusIndex" :range="DICT.infra_boolean_string" range-key="label">
				<view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding">
					<view class="justify-content-item tn-flex-1">
						<view class="tn-text-bold tn-text-lg">
							锁定状态
						</view>
						<view class="tn-color-gray tn-padding-top-xs" v-if="lockStatusIndex===99">
							请选择
						</view>
						<view class="tn-color-black tn-padding-top-xs" v-else>
							{{DICT.infra_boolean_string[lockStatusIndex].label}}
						</view>
					</view>
					<view class="justify-content-item tn-text-lg tn-color-grey tn-margin-left">
						<view class="tn-icon-right tn-padding-top"></view>
					</view>
				</view>
			</picker>

			<!-- 成交状态 -->
			<picker @change="bindDealStatusChange" :value="dealStatusIndex" :range="DICT.infra_boolean_string" range-key="label">
				<view class="tn-flex tn-flex-row-between tn-strip-bottom-min tn-padding">
					<view class="justify-content-item tn-flex-1">
						<view class="tn-text-bold tn-text-lg">
							成交状态
						</view>
						<view class="tn-color-gray tn-padding-top-xs" v-if="dealStatusIndex===99">
							请选择
						</view>
						<view class="tn-color-black tn-padding-top-xs" v-else>
							{{DICT.infra_boolean_string[dealStatusIndex].label}}
						</view>
					</view>
					<view class="justify-content-item tn-text-lg tn-color-grey tn-margin-left">
						<view class="tn-icon-right tn-padding-top"></view>
					</view>
				</view>
			</picker>

			<!-- 悬浮按钮-->
			<view class="tn-flex tn-footerfixed tn-padding">
				<view class="tn-flex-1 justify-content-item tn-text-center">
					<tn-button backgroundColor="#00C8B0 " padding="40rpx 0" width="60%" :fontSize="28"
						fontColor="#FFFFFF" shape="round" @click="submitForm">
						<text class="">保存修改</text>
					</tn-button>
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	import template_page_mixin from '@/libs/mixin/template_page_mixin.js'
	import {
		getCustomerDetail,
		updateCustomer
	} from '@/api/crm/customer.js'
	
	export default {
		name: 'CustomerEdit',
		mixins: [template_page_mixin],

		data() {
			return {
				customerId: null,
				
				// 时间选择器配置
				timeParams: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: false
				},
				showTimePicker: false,
				startYear: 2023,
				endYear: 2100,

				// 客户来源选择
				sourceIndex: 99,

				// 客户级别选择
				levelIndex: 99,

				// 客户行业选择
				industryIndex: 99,

				// 锁定状态选择
				lockStatusIndex: 99,

				// 成交状态选择
				dealStatusIndex: 99,

				// 表单数据
				formData: {
					name: '', // 客户名称
					source: '', // 客户来源
					mobile: '', // 手机号码
					telephone: '', // 固定电话
					email: '', // 邮箱地址
					level: '', // 客户级别
					industryId: '', // 客户行业
					contactNextTime: '', // 下次联系时间
					detailAddress: '', // 详细地址
					remark: '', // 备注信息
					lockStatus: '', // 锁定状态
					dealStatus: '' // 成交状态
				}
			}
		},
		
		onLoad(options) {
			if (options.id) {
				this.customerId = options.id
				this.loadCustomerDetail()
			}
		},
		
		methods: {
			// 加载客户详情
			async loadCustomerDetail() {
				try {
					uni.showLoading({
						title: '加载中...'
					})
					
					const response = await this.api.get(`/crm/customer/get?id=${this.customerId}`)
					if (response) {
						this.formData = { ...response }
						this.setPickerIndexes()
					}
				} catch (error) {
					console.error('加载客户详情失败:', error)
					uni.showToast({
						title: '加载失败，请重试',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},
			
			// 设置选择器索引
			setPickerIndexes() {
				// 设置客户来源索引
				if (this.formData.source && this.DICT.crm_customer_source) {
					const sourceIndex = this.DICT.crm_customer_source.findIndex(item => item.value === this.formData.source)
					this.sourceIndex = sourceIndex !== -1 ? sourceIndex : 99
				}
				
				// 设置客户级别索引
				if (this.formData.level && this.DICT.crm_customer_level) {
					const levelIndex = this.DICT.crm_customer_level.findIndex(item => item.value === this.formData.level)
					this.levelIndex = levelIndex !== -1 ? levelIndex : 99
				}
				
				// 设置客户行业索引
				if (this.formData.industryId && this.DICT.crm_customer_industry) {
					const industryIndex = this.DICT.crm_customer_industry.findIndex(item => item.value === this.formData.industryId)
					this.industryIndex = industryIndex !== -1 ? industryIndex : 99
				}
				
				// 设置锁定状态索引
				if (this.formData.lockStatus && this.DICT.infra_boolean_string) {
					const lockStatusIndex = this.DICT.infra_boolean_string.findIndex(item => item.value === this.formData.lockStatus)
					this.lockStatusIndex = lockStatusIndex !== -1 ? lockStatusIndex : 99
				}
				
				// 设置成交状态索引
				if (this.formData.dealStatus && this.DICT.infra_boolean_string) {
					const dealStatusIndex = this.DICT.infra_boolean_string.findIndex(item => item.value === this.formData.dealStatus)
					this.dealStatusIndex = dealStatusIndex !== -1 ? dealStatusIndex : 99
				}
			},

			// 客户来源选择
			bindSourceChange(e) {
				this.sourceIndex = e.detail.value
				this.formData.source = this.DICT.crm_customer_source[e.detail.value].value
			},

			// 客户级别选择
			bindLevelChange(e) {
				this.levelIndex = e.detail.value
				this.formData.level = this.DICT.crm_customer_level[e.detail.value].value
			},

			// 客户行业选择
			bindIndustryChange(e) {
				this.industryIndex = e.detail.value
				this.formData.industryId = this.DICT.crm_customer_industry[e.detail.value].value
			},

			// 锁定状态选择
			bindLockStatusChange(e) {
				this.lockStatusIndex = e.detail.value
				this.formData.lockStatus = this.DICT.infra_boolean_string[e.detail.value].value
			},

			// 成交状态选择
			bindDealStatusChange(e) {
				this.dealStatusIndex = e.detail.value
				this.formData.dealStatus = this.DICT.infra_boolean_string[e.detail.value].value
			},

			// 显示时间选择器
			showTimePicker() {
				this.showTimePicker = true
			},

			// 确认时间选择
			confirmTimePicker(event) {
				this.formData.contactNextTime =
					`${event.year}-${event.month}-${event.day} ${this.timeParams.hour ? event.hour+':' : ''}${this.timeParams.minute ? event.minute : ''}`
			},

			// 提交表单
			submitForm() {
				// 验证必填字段
				if (!this.formData.name.trim()) {
					uni.showToast({
						title: '请输入客户名称',
						icon: 'none'
					})
					return
				}

				if (!this.formData.source) {
					uni.showToast({
						title: '请选择客户来源',
						icon: 'none'
					})
					return
				}

				// 验证手机号格式
				if (this.formData.mobile && !/^1[3-9]\d{9}$/.test(this.formData.mobile)) {
					uni.showToast({
						title: '手机号格式不正确',
						icon: 'none'
					})
					return
				}

				// 验证邮箱格式
				if (this.formData.email && !/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(this.formData.email)) {
					uni.showToast({
						title: '邮箱格式不正确',
						icon: 'none'
					})
					return
				}

				// 显示加载提示
				uni.showLoading({
					title: '保存中...'
				})

				// 准备提交数据
				const submitData = {
					id: this.customerId,
					name: this.formData.name.trim(),
					source: this.formData.source,
					mobile: this.formData.mobile || null,
					telephone: this.formData.telephone || null,
					email: this.formData.email || null,
					level: this.formData.level || null,
					industryId: this.formData.industryId || null,
					contactNextTime: this.formData.contactNextTime ? new Date(this.formData.contactNextTime)
						.getTime() : null,
					detailAddress: this.formData.detailAddress || null,
					remark: this.formData.remark || null,
					lockStatus: this.formData.lockStatus || '0',
					dealStatus: this.formData.dealStatus || '0'
				}

				// 调用API接口
				console.log('提交数据:', submitData)
				this.api.put('/crm/customer/update', submitData).then(response => {
					uni.showToast({
						title: '客户信息更新成功',
						icon: 'success'
					})

					// 延迟返回上一页
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* 胶囊*/
	.tn-custom-nav-bar__back {
		width: 60%;
		height: 100%;
		position: relative;
		display: flex;
		justify-content: space-evenly;
		align-items: center;
		box-sizing: border-box;
		background-color: rgba(0, 0, 0, 0.15);
		border-radius: 1000rpx;
		border: 1rpx solid rgba(255, 255, 255, 0.5);
		color: #FFFFFF;
		font-size: 32rpx;

		.icon {
			display: block;
			flex: 1;
			margin: auto;
			text-align: center;
		}
	}

	.oa-content {
		max-width: 640px;
		margin: 0 auto;
		min-height: 100vh;
		padding-bottom: 60rpx;
		padding-bottom: calc(80rpx + env(safe-area-inset-bottom) / 2);
		padding-bottom: calc(80rpx + constant(safe-area-inset-bottom));
	}

	/* 间隔线 start*/
	.tn-strip-bottom-min {
		width: 100%;
		border-bottom: 1rpx solid #F8F9FB;
	}

	.tn-strip-top {
		width: 100%;
		border-top: 20rpx solid rgba(241, 241, 241, 0.8);
	}

	/* 间隔线 end*/

	/* 底部悬浮按钮 start*/
	.tn-tabbar-height {
		min-height: 160rpx;
		height: calc(180rpx + env(safe-area-inset-bottom) / 2);
		height: calc(180rpx + constant(safe-area-inset-bottom));
	}

	.tn-footerfixed {
		max-width: 640px;
		margin: 0 auto;

		width: 100%;
		bottom: calc(40rpx + env(safe-area-inset-bottom));
		z-index: 1024;
		box-shadow: 0 1rpx 6rpx rgba(0, 0, 0, 0);
	}

	/* 底部悬浮按钮 end*/
</style>